package com.team7.happycommunity.personcentor.controller;

import com.sun.mail.imap.protocol.ID;
import com.team7.happycommunity.personcentor.common.CommonResult;
import com.team7.happycommunity.personcentor.common.LoginToken;
import com.team7.happycommunity.personcentor.entity.Dynamic;
import com.team7.happycommunity.personcentor.entity.MyPublishAcitivity;
import com.team7.happycommunity.personcentor.entity.PersonUser;
import com.team7.happycommunity.personcentor.exception.LoginException;
import com.team7.happycommunity.personcentor.exception.MailboxStatusException;
import com.team7.happycommunity.personcentor.service.PersonUserService;
import com.team7.happycommunity.personcentor.util.CookieUtils;
import com.team7.happycommunity.personcentor.util.QiniuUploadUtil;
import io.swagger.annotations.*;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * (PersonUser)表控制层
 *
 * @author makejava
 * @since 2020-03-20 19:21:36
 */
@RestController
@RequestMapping("personUser")
@Api(tags="用户接口")
public class PersonUserController {
    /**
     * 服务对象
     */
    @Resource
    private PersonUserService personUserService;


    @Resource
    CookieUtils cookieUtils;

    @Autowired
    private  HttpServletRequest request;

    @Resource
    private HttpServletResponse response;

    private String realName;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public PersonUser selectOne(Integer id) {
        return this.personUserService.queryById(id);
    }

    /**
     *
     * @param text 登录的手机号或者邮箱
     * @param password 密码
     * @return
     */
    @RequestMapping("/subLogin")
    @ResponseBody
    @ApiOperation(value = "登录")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "text",value = "登录的手机号或者邮箱",required = true),
            @ApiImplicitParam(name = "password",value = "密码",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "登录成功"),
            @ApiResponse(code = 500,message = "登录失败")
    })
    public CommonResult login(String text, String password) throws Exception {
        PersonUser user =null;
        if(text==null||password==null){
            return CommonResult.failed("账号或密码不能为空");
        }
        try {
            user =personUserService.login(text, password);
        } catch (LoginException e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
        LoginToken loginToken=new LoginToken();
        loginToken.setUserId(user.getId());
        loginToken.setUsername(user.getName());
        return CommonResult.success("登录成功",loginToken);
    }

    /**
     * 发送邮件
     * @param user
     * @return
     */
    @PostMapping("/mailboxRegister")
    @ResponseBody
    @ApiOperation(value = "发送邮件")
    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "邮件发送成功"),
            @ApiResponse(code = 500,message = "邮件发送失败")
    })
   public CommonResult mailboxRegister(PersonUser user){
      //1.搜索邮箱，邮箱不存在或邮箱状态不为0
        boolean flag=personUserService.queryMailbox(user.getMailbox());
        // 2.发送邮件，存储邮箱，并将mailbox_status状态改为1，并随机生成一个code邮箱令牌，并存储到数据库
         if(flag){
             try {
                 personUserService.register(user);
                 return CommonResult.success("邮件发送成功，请激活");
             } catch (Exception e) {
                 e.printStackTrace();
                 return CommonResult.failed("邮箱不正确");
             }
         }else{
             return CommonResult.failed("邮箱已被注册");
         }
   }

    /**
     * 发送验证码
     * @param phone 手机号码
     * @param resetCode 密码重置参数，1密码重置，0注册
     * @return
     */
    @PostMapping("/phoneRegister")
    @ResponseBody
    @ApiOperation(value = "发送验证码")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phone",value = "手机号码",required = true),
            @ApiImplicitParam(name = "resetCode",value = "密码重置参数，1密码重置，0注册",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "验证码发送成功"),
            @ApiResponse(code = 500,message = "验证码发送失败")
    })
    public CommonResult phoneRegister(String phone,String resetCode){

        try {
            personUserService.phoneRegister(phone,resetCode);
            return CommonResult.success("验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 验证码校正
     * @param phone 电话号码
     * @param code 验证码
     * @return
     */
    @PostMapping("/codeCheck")
    @ResponseBody
    @ApiOperation(value = "验证码校正")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "phone",value = "手机号码",required = true),
            @ApiImplicitParam(name = "code",value = "验证码",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "校正成功"),
            @ApiResponse(code = 500,message = "校正失败")
    })
    public CommonResult codeCheck(String phone,String code){
        try {
            personUserService.codeCheck(code,phone);
            return CommonResult.success(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     * 添加个人信息
     * @param user
     * @return
     */
    @PostMapping("/addInfo")
    @ResponseBody
    @ApiOperation(value = "添加个人信息")
    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "添加成功"),
            @ApiResponse(code = 500,message = "添加失败")
    })
    public CommonResult addInfo(PersonUser user){
        if(user.getPassword()==null){
            return CommonResult.failed("注册失败，密码不能为空");
        }
        try {
            personUserService.insert(user);
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
    }
    /**
     * 修改邮箱状态
     * @param code 邮箱的令牌
     * @return
     */
   @GetMapping("/activate")
   @ResponseBody
   @ApiOperation(value = "修改邮箱状态")
   @ApiImplicitParams(value = {
           @ApiImplicitParam(name = "code",value = "邮箱的令牌")
   })

   @ApiResponses(value = {
           @ApiResponse(code = 200,message = "激活成功"),
           @ApiResponse(code = 500,message = "激活失败")
   })
    public CommonResult activate(String code){
          //激活邮箱
       ModelAndView mv=new ModelAndView();
        try {
            personUserService.updateMailboxStatus(code);
           mv.setViewName("mailboxRegisterMessage");
           return CommonResult.success("激活成功");
        }catch (MailboxStatusException e){
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }

    }

    /**
     * 密码修改
     * @param cellPhNumber 手机号码
     * @param password 新密码
     * @return
     */
    @PostMapping("/resetPassword")
    @ApiOperation(value = "密码修改")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "cellPhNumber",value = "手机号"),
            @ApiImplicitParam(name = "password",value = "新密码")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "修改成功"),
            @ApiResponse(code = 500,message = "修改失败")
    })
   public CommonResult resetPasswordByPhone(String cellPhNumber,String password){
       if (password==null){
           return CommonResult.failed("密码不能为空");
       }
        try {
            personUserService.updatePasswordByCellPhNumber(cellPhNumber,password);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("修改失败");
        }
    }

    /**
     * 个人中心,账户管理
     * @param
     * @return
     */
    @GetMapping("/personCenter")
    @ResponseBody
    @ApiOperation(value = "个人中心,账户管理")
    public CommonResult personCenter(){
        String name = request.getHeader("userName");
        if(name==null){
            return CommonResult.failed("未登录");
        }
        PersonUser user=personUserService.queryPersonInfoByName(name);
        return CommonResult.success(user);
    }
    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/exit")
    @ResponseBody
    @ApiOperation(value = "退出登录")
    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "退出成功"),
            @ApiResponse(code = 500,message = "退出失败")
    })
    public CommonResult exit(){
        String name = request.getHeader("userName");
        if(name==null){
            return CommonResult.failed("退出失败");
        }
        Cookie[] cookies = request.getCookies();
        try{
            for(int i=0;i<cookies.length;i++){
                Cookie cookie = new Cookie("bbs_0001",null);
                cookie.setMaxAge(0);
                cookie.setPath("/");//根据你创建cookie的路径进行填写
                response.addCookie(cookie);
            }
            realName=name;
            return CommonResult.success("退出成功");
        }catch(Exception ex){
            return CommonResult.failed("退出失败");
        }
    }

    /**
     * 密码修改
     * @param oldPassword 旧密码
     * @param password 新密码
     * @return
     */
    @PostMapping(value="/resetPasswordBypassword")
    @ResponseBody
    @ApiOperation(value = "密码修改")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "oldPassword",value = "旧密码",required = true),
            @ApiImplicitParam(name = "password",value = "新密码",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "修改成功"),
            @ApiResponse(code = 500,message = "修改失败")
    })
    public CommonResult resetPasswordBypassword(String oldPassword,String password){
        if (password==null||password.equals("")||oldPassword==null||oldPassword.equals("")){
            return CommonResult.failed("密码不能为空");
        }
        String name = request.getHeader("userName");
        if(name==null){
            return CommonResult.failed("未登录");
        }
        try {
            personUserService.updatePasswordBypassword(name,oldPassword,password);
            return CommonResult.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(e.getMessage());
        }
    }

    /**
     *  帖子动态
     * @return
     */
    @GetMapping("/dynamic")
    @ApiOperation(value = "帖子动态")
    public List<Dynamic> dynamic(){
        String name = request.getHeader("userName");
        if(name==null){
            return null;
        }
        List<Dynamic> user=personUserService.queryDynamicInfoByName(name);
        return user;
    }

    /**
     * 我发布的活动
     * @return
     */
    @GetMapping("/myPublishAcitivity")
    @ApiOperation(value = "我发布的活动")
    public List<MyPublishAcitivity> myPublishAcitivity(){
        String name = request.getHeader("userName");
        if(name==null){
            return null;
        }
        List<MyPublishAcitivity> acitivity=personUserService.queryMyPublishAcitivity(name);
        return acitivity;
    }

    /**
     * 活动详情
     * @param acid 活动id
     * @return
     */
    @GetMapping("/acitivityDetail")

    public List<MyPublishAcitivity> acitivityDetail(String acid){

        return null;
    }

    /**
     * 我参加的活动
     * @return
     */
    @GetMapping("/myJoinAcitivity")
    @ApiOperation(value = "我参加的活动")
    public List<MyPublishAcitivity> myJoinAcitivity(){
        String name = request.getHeader("userName");
        if(name==null){
            return null;
        }
        List<MyPublishAcitivity> acitivity=personUserService.queryJoinAcitivity(name);
        return acitivity;
    }

    /**
     *  我收藏的帖子
     * @return
     */
    @GetMapping("/myAttentionDynamic")
    @ApiOperation(value = "我收藏的帖子")
    public List<Dynamic> myAttentionDynamic(){
        String userName = request.getHeader("userName");
        if(userName==null){
            return null;
        }
        List<Dynamic> user=personUserService.queryMyAttentionDynamicByName(userName);
        return user;
    }

    /**
     * 上传头像
     * @param file
     * @return
     */
    @ResponseBody
    @PostMapping("/uploadHeadImage")
    @ApiOperation(value = "上传头像")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "图片",required = true)
    })

    @ApiResponses(value = {
            @ApiResponse(code = 200,message = "上传成功"),
            @ApiResponse(code = 500,message = "上传失败")
    })
    public CommonResult uploadHeadImage(MultipartFile file){
        String userName = request.getHeader("userName");
        if(userName==null){
            return null;
        }
        String name= UUID.randomUUID().toString().replace("_","");
        String imgurl = null;
        try {
            imgurl = new QiniuUploadUtil().upload(name, file.getBytes());
            //头像存储
            personUserService.updateHeadImage(userName,imgurl);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("上传失败");
        }
        Map map=new HashMap();
        map.put("src",imgurl);
        return CommonResult.success("上传成功",map);

    }

    /**
     * 测试专用
     * @param request
     * @return
     */
    @RequestMapping("/test")
    @ResponseBody
    public String test(HttpServletRequest request){
        String userName = request.getHeader("userName");
       String userId = request.getHeader("userId");

       System.out.println("request  test..."+userId);
        System.out.println("request  test..."+userName);
        return "test";
    }
}